﻿//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：EditorHelper
// *描述：EditorHelper
// *?2024 HDMCode . All rights reserved.
//* ======================================================================
using System;
using System.Runtime.InteropServices;
using UnityEditor;
using UnityEngine;

namespace HDMCode.UIFrameEditor
{
    public static class EditorHelper
    {
        /// <summary>
        /// window内建库
        /// </summary>
        /// <param name="hWnd">指定父窗口句柄</param>
        /// <param name="operation">用于指定要进行的操作</param>
        /// <param name="fileName">要执行的程序文件名</param>
        /// <param name="parameters">指定命令行参数</param>
        /// <param name="directory">用于指定默认目录</param>
        /// <param name="showCmd">程序窗口的初始显示方式</param>
        /// <returns></returns>
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        public static extern int ShellExecute(IntPtr hWnd, string operation, string fileName, string parameters, string directory, int showCmd);
        
        /// <summary>
        /// 通过指定IDE打开脚本文件，若IDE不存在则通过记事本打开
        /// </summary>
        /// <param name="scriptPath">脚本路径</param>
        /// <param name="idePath">IDE路径</param>
        public static void OpenScript(string scriptPath, string idePath)
        {
            if (EditorApplication.isPlaying)
                EditorApplication.isPlaying = false;
            if (!string.IsNullOrEmpty(idePath))
                ShellExecute(IntPtr.Zero, "open", $"" + idePath, scriptPath, "", 1);
            else
                ShellExecute(IntPtr.Zero, "open", "notepad", scriptPath, "", 1);
        }
        
        /// <summary>
        /// 通过名称添加脚本组件
        /// </summary>
        /// <param name="transform"></param>
        /// <param name="componentName"></param>
        /// <returns>返回组件</returns>
        public static Component AddComponentToString(this Transform transform, string componentName)
        {
            Component component = transform.GetComponent(componentName);
            if (component is null)
            {
                foreach (var item in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (string.Equals(item.GetName().Name, "Assembly-CSharp"))
                        return transform.gameObject.AddComponent(item.GetType(componentName));
                }
            }
            return component;
        }

        /// <summary>
        /// 创建一个可视化枚举
        /// </summary>
        /// <param name="index">默认选项</param>
        /// <param name="names">枚举选项</param>
        /// <param name="result">枚举选择结果</param>
        public static void CreatEmun(int index,string[] names,Action<int> result)
        {
            string name = names[index];
            if (GUILayout.Button(name, GUILayout.MaxWidth(800), GUILayout.MinWidth(10)))
            {
                GenericMenu menu = new GenericMenu();
                for(int i = 0 ; i < names.Length ; i++)
                {
                    if (name == names[i])
                    {
                        menu.AddItem(new GUIContent(names[i]), true, (back) =>
                        {
                            result?.Invoke(Array.IndexOf(names,(string)back));
                        }, names[i]);
                    }
                    else
                    {
                        menu.AddItem(new GUIContent(names[i]), false, (back) =>
                        {
                            result?.Invoke(Array.IndexOf(names,(string)back));
                        }, names[i]);
                    }
                }
                menu.ShowAsContext();
            }
        }

        /// <summary>
        /// 绝对路径转Unity项目路径
        /// </summary>
        /// <returns>返回转换后的路径</returns>
        public static string SystemPathChangeProjectPath(string path)
        {
            var newPath = path.Substring(path.IndexOf("Assets", StringComparison.Ordinal));
            return newPath;
        }

        /// <summary>
        /// 验证资源是否存在于配置文件中
        /// </summary>
        /// <param name="assetsName">需要验证的资源名称</param>
        /// <param name="assetsInfo">返回的资源信息</param>
        /// <returns>返回是否成功</returns>
        public static bool ContainsSetting(string assetsName,out EditorCreatDate assetsInfo)
        {
            foreach (var settingItem in EditorBaseDate.Setting.UISettings)
            {
                if (string.Equals(assetsName,settingItem.CreatName))
                {
                    assetsInfo = settingItem;
                    return true;
                }
            }
            assetsInfo = default;
            return false;
        }

        /// <summary>
        /// 验证资源是否存在于配置文件中
        /// </summary>
        /// <param name="guid">需要验证的资源Guid</param>
        /// <param name="assetsInfo">返回的资源信息</param>
        /// <returns>返回是否成功</returns>
        public static bool ContainsSettingByGuid(string guid, out EditorCreatDate assetsInfo)
        {
            foreach (var settingItem in EditorBaseDate.Setting.UISettings)
            {
                if (string.Equals(guid,settingItem.Guid))
                {
                    assetsInfo = settingItem;
                    return true;
                }
            }
            assetsInfo = default;
            return false;
        }

        /// <summary>
        /// 通过资源名称获取框架脚本路径
        /// </summary>
        /// <param name="assetsName">资源名称</param>
        /// <param name="outPath">输出路径</param>
        /// <returns>返回是否获取成功</returns>
        public static bool GetPathByName(string assetsName,out string outPath)
        {
            if (ContainsSetting(assetsName,out var value))
            {
                string framePath =$"{EditorBaseDate.Setting.ScriptPath}/{EditorBaseDate.Setting.Groups[value.Group]}/{value.CreatName}/{value.CreatName}.cs";
                outPath  = SystemPathChangeProjectPath(framePath);
                return true;
            }
            else
            {
                outPath = default;
                return false;
            }
        }
    }
}
